<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            title="新增账号绑定"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="90px">
                
                <el-form-item prop="wechat_tags" label="投放账号">
                    <el-tag size='large' v-for="tag in dynamicTags" :key="tag" class="mx-1" closable :disable-transitions="false" @close="handleClose(tag)">
                        {{tag}}
                    </el-tag>
                    <el-input v-if="wechatInputVisible" ref="InputRef" class="ml-1 w-20"  v-model="wechatInputValue"
                        size="default" @keyup.enter="handleWechatInputConfirm" @blur="handleWechatInputConfirm">
                    </el-input>
                    <el-button v-else class="button-new-tag ml-1" size="default" @click="showWechatInput"> + 新增</el-button>
                </el-form-item>

                <el-form-item>
                <el-upload
                        class="upload-demo"
                        :action="uploadUrl"
                        :headers="uploadHeaders"
                        :data="{ account_id: props.account_id }"
                        :before-upload="beforeUpload"
                        :on-success="handleUploadSuccess"
                        :show-file-list="false"
                        accept=".xls,.xlsx">
                        <el-link type="primary">解析Excel文件</el-link>
                        <template #tip>
                            <div class="el-upload__tip">
                                仅支持.xls和.xlsx格式文件，
                                <el-link type="primary" :href="templateUrl" download>下载模板</el-link>
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup  name="tencentAdvertisingUserAdListEdit" >
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import {apiTencentAdvertisingUserAdListDetail } from '@/api/tencent_advertising_user_ad_list'
import { apiTencentAdvertisingAccountWechatBind } from '@/api/tencent_advertising_account'
import { ElInput } from 'element-plus'
import type { PropType } from 'vue'
import { ElMessage } from 'element-plus'
import useUserStore from '@/stores/modules/user'

const props = defineProps({
    account_id: {
        type: String,
        default: ''
    }
})

const emit = defineEmits(['success','close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')

const userStore = useUserStore()

// 表单数据
const formData = reactive({
    account_id:props.account_id,
    wechat_list:[]
})



const dynamicTags = ref([])
const wechatInputValue = ref('')
const wechatInputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()


const handleClose  = (tag: string) => {
    dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showWechatInput = () => {
    wechatInputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}


const handleWechatInputConfirm = () => {
  if (wechatInputValue.value) {
    dynamicTags.value.push(wechatInputValue.value)
  }
  wechatInputVisible.value = false
  wechatInputValue.value = ''
}


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    // formData.value.id=data.id
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiTencentAdvertisingUserAdListDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    // formData.value.wechat_list=tag_wechats
    const data = { ...formData,...{wechat_list:dynamicTags.value} }

    mode.value == await apiTencentAdvertisingAccountWechatBind(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}
// 文件上传头信息
const uploadHeaders = computed(() => ({
    Token: userStore.token,
}))

// 文件上传相关
const uploadUrl = `${import.meta.env.VITE_APP_BASE_URL || ''}/tenantapi/ads.tencent_advertising_account/get_file_data` // 根据实际API接口调整
const templateUrl = `${import.meta.env.VITE_APP_BASE_URL || ''}/uploads/wechat_import_template.xlsx` // 模板文件路径

const beforeUpload = (file: File) => {
    const isExcel = file.type === 'application/vnd.ms-excel' 
        || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    const isLt10M = file.size / 1024 / 1024 < 10

    if (!isExcel) {
        ElMessage.error('仅支持Excel文件格式!')
    }
    if (!isLt10M) {
        ElMessage.error('文件大小不能超过10MB!')
    }
    return isExcel && isLt10M
}

const handleUploadSuccess = (response: any) => {
    console.log(response,'response.dataresponse.dataresponse.dataresponse.data');
    if (response.code === 1) {
        // 处理上传成功的逻辑
        // dynamicTags.value = response.data.wechats
        ElMessage.success('文件上传成功')
        dynamicTags.value = response.data
    } else {
        ElMessage.error(response.msg)
    }
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
